#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : gtmsAutoTestProject 
@File    : mysqlControl.py
@IDE     : PyCharm 
@Author  : Mario
@Date    : 2022/5/11 11:47 
@Describe:
"""
import pymysql
from Config.yamlRead import mysqlInfo_cfg
from Comm.logUtils.logControl import LogHandler


class MysqlHandler:
    def __init__(self, database_name):
        self.logger = LogHandler().get_logger()
        self.logger.debug('正在连接[{}]数据库.'.format(database_name))
        self.conn = pymysql.connect(
            host=mysqlInfo_cfg['host'],
            port=mysqlInfo_cfg['port'],
            user=mysqlInfo_cfg[database_name]['user'],
            password=mysqlInfo_cfg[database_name]['password'],
            database=mysqlInfo_cfg[database_name]['database'],
            charset='utf8'
        )
        # 使用 cursor() 方法创建一个游标对象 cursor
        self.cursor = self.conn.cursor()

    def close(self):
        """
        关闭数据库连接
        :return:
        """
        self.cursor.close()
        self.conn.close()
        self.logger.debug('正在关闭数据库连接.')

    def table_select(self, select_sql, one=True):
        """
        数据库查询
        :param select_sql: 查询语句
        :param one: 是否多条数据,默认单条数据
        :return:
        """
        try:
            self.cursor.execute(select_sql)
            self.logger.debug('正在执行查询数据操作,查询语句:[{}]'.format(select_sql))
            if one:
                select_result_data = self.cursor.fetchone()
                if select_result_data:  # 判断取出的值是否不为None
                    if len(select_result_data) == 1:  # 判断长度是否等于1
                        return select_result_data[0]  # 长度为1的话把对应值取出
                    return select_result_data
            else:
                select_result_data = self.cursor.fetchall()
                return select_result_data
        except:
            self.close()

    def table_insert(self, insert_sql):
        """
        数据库插入数据
        :param insert_sql: 插入语句
        :return:
        """
        try:
            insert_result_data = self.cursor.execute(insert_sql)
            self.conn.commit()
            self.logger.info('正在执行插入数据操作,插入语句:[{}]'.format(insert_sql))
            return insert_result_data
        except:
            self.logger.warning('正在回滚插入数据操作,插入语句:[{}]'.format(insert_sql))
            self.conn.rollback()
            self.close()

    def table_updated(self, updated_sql):
        """
        数据库更新数据
        :param updated_sql: 更新语句
        :return:
        """
        try:
            updated_result_data = self.cursor.execute(updated_sql)
            self.conn.commit()
            self.logger.info('正在执行更新数据操作,更新语句:[{}],影响条数:[{}]'.format(updated_sql, str(updated_result_data)))
            return updated_result_data
        except:
            self.logger.warning('正在回滚更新数据操作,更新语句:[{}]'.format(updated_sql))
            self.conn.rollback()
            self.close()
